import os
import json
import csv
from datetime import datetime
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton, 
                            QTableWidget, QTableWidgetItem, QHeaderView, 
                            QFileDialog, QMessageBox)
from PyQt5.QtGui import QColor, QBrush

from modules.utils.register_utils import load_registered_accounts

class ResultsTab(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.results = []
        self.init_ui()
        
    def init_ui(self):
        layout = QVBoxLayout(self)
        
        # 创建结果表格
        self.results_table = QTableWidget()
        self.results_table.setColumnCount(4)
        self.results_table.setHorizontalHeaderLabels(["账号", "Outlook密码", "Cursor密码", "Token"])
        self.results_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.results_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.results_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.results_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
        layout.addWidget(self.results_table)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        # 刷新按钮
        refresh_button = QPushButton("刷新结果")
        refresh_button.clicked.connect(self.refresh_results)
        button_layout.addWidget(refresh_button)
        
        # 导出按钮组
        export_json_button = QPushButton("导出JSON")
        export_json_button.clicked.connect(self.export_json)
        button_layout.addWidget(export_json_button)
        
        export_excel_button = QPushButton("导出Excel")
        export_excel_button.clicked.connect(self.export_excel)
        button_layout.addWidget(export_excel_button)
        
        export_sql_button = QPushButton("导出SQL")
        export_sql_button.clicked.connect(self.export_sql)
        button_layout.addWidget(export_sql_button)
        
        layout.addLayout(button_layout)
        
        # 加载初始结果
        self.refresh_results()
    
    def refresh_results(self):
        """刷新注册结果"""
        # 加载已注册账号
        registered_accounts = load_registered_accounts()
        
        # 转换为列表格式
        self.results = list(registered_accounts.values())
        
        # 更新表格
        self.update_table()
    
    def update_table(self):
        """更新表格内容"""
        self.results_table.setRowCount(0)
        
        for result in self.results:
            row = self.results_table.rowCount()
            self.results_table.insertRow(row)
            
            # 添加账号信息
            self.results_table.setItem(row, 0, QTableWidgetItem(result.get("username", "")))
            self.results_table.setItem(row, 1, QTableWidgetItem(result.get("outlook_password", "")))
            self.results_table.setItem(row, 2, QTableWidgetItem(result.get("cursor_password", "")))
            
            # 添加Token（可能较长，只显示部分）
            token = result.get("token", "")
            token_display = token[:20] + "..." if token and len(token) > 20 else token
            token_item = QTableWidgetItem(token_display)
            if token:
                token_item.setToolTip(token)  # 显示完整token作为提示
            self.results_table.setItem(row, 3, token_item)
    
    def update_results(self, new_results):
        """更新结果（从外部调用）"""
        if not new_results:
            return
            
        # 将新结果添加到现有结果中
        for result in new_results:
            if result not in self.results:
                self.results.append(result)
        
        # 更新表格
        self.update_table()
    
    def export_json(self):
        """导出结果为JSON格式"""
        if not self.results:
            QMessageBox.warning(self, "警告", "没有可导出的结果")
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出JSON", f"cursor_accounts_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", "JSON文件 (*.json)"
        )
        
        if not file_path:
            return
            
        try:
            # 准备导出数据
            export_data = {"accounts": self.results}
            
            # 写入文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(export_data, f, indent=4, ensure_ascii=False)
                
            QMessageBox.information(self, "成功", f"已成功导出 {len(self.results)} 个账号到 {file_path}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出JSON失败: {str(e)}")
    
    def export_excel(self):
        """导出结果为Excel格式（CSV）"""
        if not self.results:
            QMessageBox.warning(self, "警告", "没有可导出的结果")
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出Excel", f"cursor_accounts_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv", "CSV文件 (*.csv)"
        )
        
        if not file_path:
            return
            
        try:
            # 准备表头
            fieldnames = ["username", "outlook_password", "cursor_password", "token"]
            
            # 写入文件
            with open(file_path, 'w', newline='', encoding='utf-8') as f:
                writer = csv.DictWriter(f, fieldnames=fieldnames)
                writer.writeheader()
                
                # 只写入指定字段
                for result in self.results:
                    row = {field: result.get(field, "") for field in fieldnames}
                    writer.writerow(row)
                
            QMessageBox.information(self, "成功", f"已成功导出 {len(self.results)} 个账号到 {file_path}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出Excel失败: {str(e)}")
    
    def export_sql(self):
        """导出结果为SQL插入语句"""
        if not self.results:
            QMessageBox.warning(self, "警告", "没有可导出的结果")
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出SQL", f"cursor_accounts_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql", "SQL文件 (*.sql)"
        )
        
        if not file_path:
            return
            
        try:
            # 准备SQL语句
            table_name = "cursor_accounts"
            sql_lines = [
                "-- Cursor账号数据",
                f"-- 导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                "",
                f"CREATE TABLE IF NOT EXISTS `{table_name}` (",
                "  `id` int(11) NOT NULL AUTO_INCREMENT,",
                "  `username` varchar(255) NOT NULL,",
                "  `outlook_password` varchar(255) DEFAULT NULL,",
                "  `cursor_password` varchar(255) DEFAULT NULL,",
                "  `token` text DEFAULT NULL,",
                "  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,",
                "  PRIMARY KEY (`id`),",
                "  UNIQUE KEY `username` (`username`)",
                ");",
                ""
            ]
            
            # 生成INSERT语句
            for result in self.results:
                username = result.get("username", "").replace("'", "''")
                outlook_pw = result.get("outlook_password", "").replace("'", "''")
                cursor_pw = result.get("cursor_password", "").replace("'", "''")
                token = result.get("token", "").replace("'", "''")
                
                sql = f"INSERT INTO `{table_name}` (`username`, `outlook_password`, `cursor_password`, `token`) VALUES "
                sql += f"('{username}', '{outlook_pw}', '{cursor_pw}', '{token}');"
                sql_lines.append(sql)
            
            # 写入文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write("\n".join(sql_lines))
                
            QMessageBox.information(self, "成功", f"已成功导出 {len(self.results)} 个账号到 {file_path}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出SQL失败: {str(e)}") 